import { _decorator, Component, Node, instantiate, Prefab } from 'cc';
import { ResourceManager } from './ResourceManager';
const { ccclass } = _decorator;

/**
 * Jees.UI
 * 全局UI管理器
 */
@ccclass("J_UIManager")
export class UIManager extends Component {

    // 当前组件根画布节点
    private Canvas: Node | null = null;
    // 当前组件子UI集合
    private uiMap: Record<string, Node | null> = {};

    // 管理器初始化
    static init(_jees: any, _node: Node) {
        _jees.UI = _node.addComponent(UIManager)
    }

    // 初始根画布化节点
    onLoad() {
        this.Canvas = this.node;
    }

    /**
     * 显示某个UI预制体
     * @param _ui_name UI名称
     * @param _parent 父节点
     * 如果UI未创建过，则新添加于父节点下，如果没有父节点则默认根Canvas节点
     */
    showUI(_ui_name: string, _parent?: Node | null): Node | null {
        if (!_parent) _parent = this.Canvas;
        if (this.uiMap[_ui_name]) {
            (this.uiMap[_ui_name] as Node).active = true;
            return null;
        }
        let item: Node | null = null;
        ResourceManager.setPrefabs('prefabs', _ui_name, (_prefab: Prefab) => {
            if (_prefab) {
                item = instantiate(_prefab);
                _parent?.addChild(item);
                item.addComponent(_ui_name + '_Ctrl');
            }
            this.uiMap[_ui_name] = item;
        });
        return item;
    }

    /**
     * 隐藏某个UI预制体
     * @param _ui_name UI名称
     */
    hideUI(_ui_name: string) {
        let comp = this.Canvas?.getChildByName(_ui_name);
        if (!comp) return;
        comp.active = false;
    }

    /**
     * 删除某个UI预制体
     * @param _ui_name UI名称
     */
    removeUI(_ui_name: string) {
        if (this.uiMap[_ui_name]) {
            this.uiMap[_ui_name]?.removeFromParent();
            this.uiMap[_ui_name] = null;
        }
    }

    /**
     * 清空所有子UI预制体
     */
    clearAll() {
        for (let _ui_name in this.uiMap) {
            if (this.uiMap[_ui_name]) {
                this.uiMap[_ui_name]?.removeFromParent();
                this.uiMap[_ui_name] = null;
            }
        }
    }

}